package com.genericdao.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.genericdao.intf.BaseDao;

/**
 * dao 基类，实现通用 dao 接口，被实体 dao 类继承
 * @author lin
 *
 * @param <T>
 */
public class BaseDaoImpl<T> implements BaseDao<T> {
	
	/**
	 * 用于确定具体实体 dao 的泛型实际类型
	 */
	private Class<T> type;
	
	/**
	 *由 Spring 注入sessionfactory
	 */
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Class<T> getType() {
		return type;
	}

	public void setType(Class<T> type) {
		this.type = type;
	}

	@Override
	public void create(T t) {
		
		if(t != null)
		{
			Session session = sessionFactory.getCurrentSession();
			
			session.save(t);
		}
		
	}

	@Override
	public T read(Integer id) {
		
		if(id != null)
		{
			Session session = sessionFactory.getCurrentSession();
			
			return (T) session.get(type, id);
		}
		
		return null;
	}

	@Override
	public void update(T t) {
		
		if(t != null)
		{
			Session session = sessionFactory.getCurrentSession();
			
			session.update(t);
		}
		
	}

	@Override
	public void delete(T t) {
		
		if(t != null)
		{
			Session session = sessionFactory.getCurrentSession();
			
			session.delete(t);
		}
		
	}
	
	@Override
	public void delete(Integer id)
	{
		if(id != null)
		{
			this.delete(this.read(id));
		}
	}

	@Override
	public List<T> listAll() {
		
		Session session = sessionFactory.getCurrentSession();
		
		Criteria criteria = session.createCriteria(type);
		
		List<T> list = criteria.list();
		
		return list;
	}
	
	@Override
	public List<T> listAll(String hql, Object... parameters) {
		
		if(hql != null && !hql.equals("") && parameters.length != 0)
		{
			Session session = sessionFactory.getCurrentSession();
			
			Query query = session.createQuery(hql);
			
			for(int i = 0;i<parameters.length;i++)
			{
				query.setParameter(i, parameters[i]);
			}
			
			return query.list();
		}
		
		return null;
	}

}
